package net.hangar5.xmlrpc;

/* HttpResponse.java

The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.

The Original Code is "Hangar5 XMLRPC Library".

The Initial Developer of the Original Code is James D. Rudnicki.
Portions created by James D. Rudnicki are
Copyright (C) 2001.  All Rights Reserved.

Contributor(s):
*/
import java.util.StringTokenizer;
import java.io.*;

/**
 * The response from a HTTP PUT or POST is encapsulated in this
 * class.  Instances of this class are obtained from the HttpClient.
 */
public class HttpResponse
{
  private int nStatusCode;
  private int nContentLength;
  private boolean bServerSaysKeepAlive;

  private BufferedReader rdIn;
  private char[] chResponse;
  private boolean bHasResponse;

  /**
   * Constructs object from stream.
   */
  public HttpResponse( BufferedInputStream in )
  {
	rdIn = new BufferedReader(new InputStreamReader( in ));
	nStatusCode = 0;
	nContentLength = 0;
	bHasResponse = false;
  }

  /** Response content as a string
   */
  public String getContent()
  {
	if( !bHasResponse )
        {
	  try
          {
		readHeader();
		chResponse = readContent();

		bHasResponse = true;
	  }
	  catch( IOException x )
          {
		bHasResponse = false;
		chResponse = null;
	  }
	}
	String str = null;
	if( chResponse != null )
        {
	  str = new String(chResponse);
	}
	return str;
  }
  /** Response content block length
   */
  public int getContentLength()
  {
	return nContentLength;
  }
  /** HTTP status code response
   */
  public int getStatusCode()
  {
	return nStatusCode;
  }
  public void read()
  {
	try {
	  readHeader();
	  chResponse = readContent();
	  bHasResponse = true;
	}
	catch( IOException x )
        {
	  bHasResponse = false;
	  chResponse = null;
	}
  }
  public char[] readContent() throws IOException
  {
	final int nChunk = 250;
	int nLength;
	int nUnread = nContentLength;
	int nRxd;
	char[] buffer = new char[nContentLength];
	int offset = 0;
	while( nUnread > 0 )
        {
	  /* truncate length so that the read does not go into next request */
	  nLength = Math.min(nChunk, nUnread);
	  nRxd = rdIn.read(buffer, offset, nLength);
	 /* subtract off what was actually read from the stream */
	  if( nRxd > 0 )
          {
		offset += nRxd;
		nUnread -= nRxd;
	  }
	}
	return buffer;
  }

  public void readHeader() throws IOException
  {
	String strLine;
	boolean bTryAgain;
	int nRetrys = 0;
	int nMax = 10;
	nStatusCode = 0;
	  /* first line is HTTP__ number message */
	strLine = rdIn.readLine();
	if( null==strLine )
        {
	  throw new IOException( "Server did not respond" );
	}
	try
        {
	  String strX;
	  StringTokenizer tokens = new StringTokenizer( strLine );
	  strX = tokens.nextToken();
	  strX = tokens.nextToken();
	  nStatusCode = Integer.parseInt( strX );
	  String statusMsg = tokens.nextToken ("\n\r");
	}
        catch (Exception x)
        {
	  System.err.println( strLine );
	  x.printStackTrace ();
	  throw new IOException ("Server returned invalid Response.");
	}
	if ( 200 != nStatusCode )
        {
	  rdIn.close();
	  throw new IOException ("Unexpected Response from Server: "+nStatusCode);
	}
	do
        {
	  strLine = rdIn.readLine();
	  if (strLine != null)
          {
		strLine = strLine.toLowerCase ();
		if( strLine.startsWith( "content-length:" ) )
                {
		  nContentLength = Integer.parseInt( strLine.substring(15).trim () );
		}
		else if (strLine.startsWith ("connection:"))
                {
		  bServerSaysKeepAlive = ( strLine.indexOf ("keep-alive") >= 0 );
		}

	  }
	}
        while (strLine != null && ! strLine.equals(""));
  }
} // end HttpResponse
